package com.thornbird.vehiclerecycling.config;

import com.thornbird.vehiclerecycling.util.JsonUtil;
import com.thornbird.vehiclerecycling.util.ResultUtil;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

@Order(1)
@WebFilter(filterName = "csrfFilter", urlPatterns = {"/", "/page/*", "/api/*"})
public class CsrfFilter implements Filter {

    public static final String CSRF_PARM_NAME = "csrfParm";

    public static final String CSRF_TOKEN_NAME = "csrfToken";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (request.getMethod().equals(RequestMethod.GET.name())) {
            if (request.getSession().getAttribute(CSRF_PARM_NAME) == null) {
                String token = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                request.getSession().setAttribute(CSRF_PARM_NAME, CSRF_TOKEN_NAME);
                request.getSession().setAttribute(CSRF_TOKEN_NAME, token);
            }
        } else {
            Object token = request.getSession().getAttribute(CSRF_TOKEN_NAME);
            String originalToken = token == null ? "" : token.toString();
            originalToken = originalToken == null ? "" : originalToken;
            String csrfToken = request.getHeader("csrfToken") == null ? "" : request.getHeader("csrfToken");
            if (!csrfToken.equals(originalToken)) {
                String responseText = JsonUtil.toJsonString(ResultUtil.forbiddenError());
                servletResponse.getOutputStream().print(responseText);
                servletResponse.getOutputStream().close();
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
